Unique paths

A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).

The robot can only move either down or right at any point in time.

The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).

How many possible unique paths are there?

Example 1:

Input: m = 3, n = 2

Output: 3

Explanation:

  • From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:

    1. Right -> Right -> Down

    2. Right -> Down -> Right

    3. Down -> Right -> Right

Example 2:

Input: m = 7, n = 3

Output: 28

Example 3:

Input: m = 3, n = 3

Output: 6

Explanation:

  • D : Down

  • R : Right 1) DDRR 2) DRDR 3) DRRD 4) RRDD 5) RDRD 6) RDDR

Constraints:

  • 1 <= m, n <= 100

  • It’s guaranteed that the answer will be less than or equal to 2 * 10 ^ 9.

[1]:
class Solution1(object):
    """
    Time: O(M*N)
    Space: O(M+N)
    """
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        if m < n:
            return self.uniquePaths(n, m)

        ways = [1] * n
        for i in range(1, m):
            for j in range(1, n):
                ways[j] += ways[j - 1]

        return ways[n - 1]
[2]:
s = Solution1()

m = 3
n = 2
assert s.uniquePaths(m, n) == 3

m = 7
n = 3
assert s.uniquePaths(m, n) == 28

m = 3
n = 3
assert s.uniquePaths(m, n) == 6